<script>
	// H5所需sdk  不用就删掉   package.json也删掉，不然会影响小程序的打包大小
	// #ifdef H5
	import TIM from 'tim-js-sdk/tim-js-friendship.js';
	import COS from 'cos-js-sdk-v5';
	// #endif

	// #ifdef MP-WEIXIN  || APP-PLUS
	import TIM from 'tim-wx-sdk/tim-wx-friendship.js';
	import COS from 'cos-wx-sdk-v5';
	// #endif
	import config from './common/config.js'
	let sdkAppID = config.imApppId;

	// APP通话插件
	// #ifdef  APP-PLUS
	const TUICallKit = uni.requireNativePlugin('TencentCloud-TUICallKit');
	TUICallKit.enableFloatWindow(true);
	console.log(TUICallKit, '通话初始化TUICallKit ｜ ok');
	// #endif
	import Vue from 'vue';

	export default {
		data() {
			return {
				versionName: "",
			};
		},
		onLaunch() {
			Vue.prototype.TIM = TIM;
			this.initialization();
			// this.timers = setInterval(() => {
				this.checkUpdate();
			// }, 5000);

			const compensateHeight = 10; //非刘海屏状态栏高度偏低，补充10
			uni.getSystemInfo({
				success: (e) => {
					// 获取手机状态栏高度
					let statusBar = e.statusBarHeight
					let customBar
					// #ifndef MP
					customBar = statusBar + (e.platform == 'android' ? 50 : 45)
					// #endif
					// #ifdef MP-WEIXIN
					// 获取胶囊按钮的布局位置信息
					let menu = wx.getMenuButtonBoundingClientRect()
					// 导航栏高度 = 胶囊下距离 + 胶囊上距离 - 状态栏高度
					customBar = menu.bottom + menu.top - statusBar
					// #endif
					// #ifdef MP-ALIPAY
					customBar = statusBar + e.titleBarHeight
					// #endif
					this.$store.commit("SET_STATUSBAR", {
						statusBar: statusBar + compensateHeight,
						customBar: customBar + compensateHeight
					})
				}
			})


		},
		onShow() {
			
		},
		globalData: {
			userInfo: null,
			userProfile: null,
			webviewUrl: '',
			headerHeight: 0,
			statusBarHeight: 0
		},
		methods: {
			// 初始化 im
			initialization() {
				const sdkID = uni.getStorageSync('sdkAppID');
				if (sdkID) {
					sdkAppID = sdkID;
				}

				// 初始化tim
				uni.$TUIKit = TIM.create({
					SDKAppID: sdkAppID
				});
				wx.$TUIKit = uni.$TUIKit;

				// #ifdef  H5
				uni.$TUIKit.registerPlugin({
					'cos-js-sdk': COS
				});
				// #endif

				// #ifdef  APP-PLUS || MP-WEIXIN
				uni.$TUIKit.registerPlugin({
					'cos-wx-sdk': COS
				});
				// #endif

				// #ifdef  APP-PLUS
				uni.$TUICallKit = TUICallKit;
				// #endif

				uni.$TUIKit.setLogLevel(3);

				uni.$TUIKitTIM = TIM;
				uni.$TUIKitEvent = TIM.EVENT;
				uni.$TUIKitVersion = TIM.VERSION;
				uni.$TUIKitTypes = TIM.TYPES; // 监听系统级事件
				uni.$resetLoginData = this.resetLoginData();

				uni.$TUIKit.on(uni.$TUIKitEvent.SDK_NOT_READY, this.onSdkNotReady);
				uni.$TUIKit.on(uni.$TUIKitEvent.KICKED_OUT, this.onKickedOut);
				uni.$TUIKit.on(uni.$TUIKitEvent.ERROR, this.onTIMError);
				uni.$TUIKit.on(uni.$TUIKitEvent.NET_STATE_CHANGE, this.onNetStateChange);
				uni.$TUIKit.on(uni.$TUIKitEvent.SDK_RELOAD, this.onSDKReload);
				uni.$TUIKit.on(uni.$TUIKitEvent.SDK_READY, this.onSDKReady);

				// 是否登录
				this.isLogin();
			},
			isLogin() {
				const userID = uni.getStorageSync('userID');
				const userSig = uni.getStorageSync('userSig');
				const userInfo = uni.getStorageSync('userInfo');
				// console.log("============",userInfo,"==========")
				if (!userID || !userInfo.token) {
					uni.navigateTo({
						url: '/im/login/login'
					});
				} else {
					// 登录im
					uni.$TUIKit
						.login({
							userID: userID,
							userSig: userSig
						})
						.then(res => {
							console.log('IM登录成功', res);
						})
						.catch(() => {});

					// 登录 native 原生通话插件
					// #ifdef  APP-PLUS
					uni.$TUICallKit.login({
							SDKAppID: sdkAppID,
							userID: userID,
							userSig: userSig
						},
						res => {
							if (res.code === 0) {
								console.log('app视频通话登录成功');
							} else {
								console.log(`app视频通话, error message = ${res.msg}`);
							}
						}
					);
					// #endif
				}
			},
			// TODO:
			resetLoginData() {
				this.globalData.expiresIn = '';
				this.globalData.sessionID = '';
				this.globalData.userInfo = {
					userID: '',
					userSig: '',
					token: '',
					phone: ''
				};
				this.globalData.userProfile = null;
			},
			onTIMError() {},
			onNetStateChange() {},
			onSDKReload() {},
			onSDKReady() {
				console.log('im-onSDKReady');
				this.$store.commit('login');
			},
			onSdkNotReady() {},
			onKickedOut() {
				setTimeout(() => {
					uni.showToast({
						title: '您被踢下线',
						icon: 'error'
					});
				}, 1000);
				uni.navigateTo({
					url: '/im/login/login'
				});
			},
			checkUpdate() {
				if (plus) {
					plus.runtime.getProperty(plus.runtime.appid, (info) => {
						this.versionName = info.version;
					});
					let now = new Date().getTime();
					let urlstr = "https://zhiyuapp.oss-cn-fuzhou.aliyuncs.com/uniapp_android/aitaConfig.json?t=" + now;
					uni.request({
						url: urlstr,
						success: (res) => {
							clearInterval(this.timers);
							

							let isaliPay = res.data.isaliPay; //isaliPay 1为开启
							let vipManage = res.data.vipManage; // 1 关闭门票
							let ticketPrice = res.data.ticketPrice; //门票价格
							
							console.log('data:' + res.data);
							console.log('versionName:' + this.versionName);
							console.log('open:' + res.data.open);
							console.log("vipManage:"+vipManage + "\t isaliPay:"+ isaliPay + '\t ticketPrice:' + ticketPrice);
							
							uni.setStorageSync('isaliPay', isaliPay);
							uni.setStorageSync('vipManage', vipManage);
							uni.setStorageSync('ticketPrice', ticketPrice);

							if (res.data.open == "1" && res.data.vss != this.versionName) {
								plus.nativeUI.showWaiting("检测更新~~~");
								this.downloadWgt(res.data.wgtUrl);
							}
						}
					})
				}
			},
			//wgt下载安装
			downloadWgt(wgtUrl) {
				if (plus) {
					plus.downloader.createDownload(wgtUrl, {
						filename: "_doc/update/"
					}, function(d, status) {
						console.log(d);
						console.log(status);
						if (status == 200) {
							plus.runtime.install(d.filename, {
								force: true
							}, function() {
								plus.nativeUI.closeWaiting();
								plus.nativeUI.alert("更新成功~~~", function() {
									plus.runtime.restart();
								});
							}, function(e) {
								plus.nativeUI.closeWaiting();
								plus.nativeUI.alert("更新失败~~~ [" + e.code + "]：" + e.message);
							});
						} else {
							plus.nativeUI.alert("下载wgt失败！");
							plus.nativeUI.closeWaiting();
						}
					}).start();
				}
			}
		}
	};
</script>

<style lang="scss">
	@import 'uview-ui/index.scss';
	@import 'static/css/index.css';
</style>